<template>
	<view class="controll">
		<view class="title">
			<view class="r">
				<view class="car_name">
					<text class="label">姓名：</text>
					<text class="value">{{ name }} </text>
				</view>
				<view class="car_name">
					<text class="label">年龄：</text>
					<text class="value">{{ age }}岁</text>
				</view>
				<view class="car_name">
					<text class="label">性别：</text>
					<text class="value">{{sexEnum[sex]}}</text>
				</view>
			</view>
		</view>
		<view class="content">
			<view class="item" v-for="(item,index) in dataList" :key="index">
				<text v-if="item.type == 0">体温：{{item.value}}°</text>
				<text v-else-if="item.type == 1">心率：{{item.value}}</text>
				<text v-else-if="item.type == 2">血氧：{{item.value}}</text>
			</view>
			<!-- 	<view class="item" @click="massageHandle"><text>血氧：89</text></view>
			<view class="item"><text>心率：{{heart}}/{{ox}}</text></view> -->
		</view>
		<view class="history">
			<text>历史数据</text>
		</view>
		<div ref="chartContainer" class="chart-container"></div>

	</view>
</template>

<script>
	// const mqtt = require("../../utils/Mqtt.js");
	// import mqtt from "../../utils/mqtt4.1.0.js"
	import * as echarts from 'echarts' // 引入ECharts库

	import {
		getHealthDataList
	} from "../../api/car.js"
	export default {
		data() {
			return {
				number: "",
				name: "",
				sex: "",
				age: "",
				dataList: [],
				temData: [],
				oxData: [],
				xlData: [],
				dateData: [],
				sexEnum: {
					0: "男",
					1: "女"
				},
				//------------------- end ------------------------
				timer: null,
				chat: null,
				option: {}
			};
		},
		onLoad(e) {
			this.number = e.number
			this.name = e.name
			this.age = e.age
			this.sex = e.sex
		},
		mounted() {
			this.getHealthDataListFun();
			// this.getOrderDetail()
			// this.connect()
			// this.timer = setInterval(() => {
			// 	this.getSubMessages()
			// }, 2000)

		},
		methods: {
			// 时间格式化函数（假设原始数据格式为 "2025-04-12T06:48:33.000+0000"）
			formatDate(isoString) {
				const date = new Date(isoString);
				// return `${date.getFullYear()}年${date.getMonth()+1}月${date.getDate()}日`;
				// return `${date.getMonth()+1}月${date.getDate()}日`;
				return `${date.getHours()+1}点${date.getMinutes()}分`;
			},
			initChart() {
				const chartContainer = this.$refs.chartContainer
				this.chart = echarts.init(chartContainer)

				this.chart.setOption(this.option) // 将配置应用到图表实例
			},
			async getHealthDataListFun() {

				const res = await getHealthDataList({
					number: this.number
				})

				console.log(res)

				if (res.code == 200) {
					try {
						// 格式化函数：将时间转换为YYYY-MM-DD格式
						const formatDate = (dateString) => {
							const date = new Date(dateString);
							return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
						};

						// 获取每种类型每天的最新数据
						const getLatestDailyData = (data) => {
							const dailyMap = {};

							data.forEach(item => {
								const dateKey = formatDate(item.createTime);
								// 如果当天没有数据，或者当前数据更新，则存入
								if (!dailyMap[dateKey] || new Date(item.createTime) > new Date(dailyMap[dateKey].createTime)) {
									dailyMap[dateKey] = item;
								}
							});

							// 转换为数组并按日期排序（从新到旧）
							return Object.values(dailyMap)
								.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
						};

						// 处理原始数据
						this.temData = getLatestDailyData(
							res.data.filter(t => t.type === 0)
						).slice(0, 5); // 体温数据，取最近5天

						this.xlData = getLatestDailyData(
							res.data.filter(t => t.type === 1)
						).slice(0, 5); // 心率数据，取最近5天

						this.oxData = getLatestDailyData(
							res.data.filter(t => t.type === 2)
						).slice(0, 5); // 血氧数据，取最近5天

						// 获取所有数据的最近5天日期（去重）
						const allDates = [
							...this.temData.map(item => formatDate(item.createTime)),
							...this.xlData.map(item => formatDate(item.createTime)),
							...this.oxData.map(item => formatDate(item.createTime))
						];
						const uniqueDates = [...new Set(allDates)]
							.sort((a, b) => new Date(b) - new Date(a))
							.slice(0, 5);

						// dateData用于x轴显示
						this.dateData = uniqueDates;

						// dataList获取各类型最新一条数据
						this.dataList = [
							this.temData[0] || null,
							this.xlData[0] || null,
							this.oxData[0] || null
						].filter(item => item !== null); // 过滤掉可能为null的数据
					} catch (e) {
						console.error("数据排序出错:", e);
					}
				}


				this.option = {
					title: {
						text: '' // 添加了图表标题
					},
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'cross' // 改为cross更符合折线图风格
						},
						formatter: function(params) {
							let result = params[0].axisValue + '<br/>';
							params.forEach(item => {
								result += `${item.marker} ${item.seriesName}: ${item.value}`;
								if (item.seriesName === '体温') result += '℃';
								else if (item.seriesName === '血氧') result += '%';
								else result += '次/分';
								result += '<br/>';
							});
							return result;
						}
					},
					legend: {
						data: ['体温', '心率', '血氧'],
						bottom: 10 // 图例放在底部
					},
					grid: {
						top: '15%',
						left: '3%',
						right: '4%',
						bottom: '15%',
						containLabel: true
					},
					xAxis: {
						type: 'category',
						axisLabel: {
							rotate: 30 // 日期标签旋转30度防止重叠
						},
						// 格式化时间为年月日（只取前5个）
						data: this.dateData.map(item => item)
					},
					yAxis: [{
							type: 'value',
							name: '体温(℃)',
							min: 35,
							max: 42,
							axisLine: {
								lineStyle: {
									color: '#FF6B6B' // 体温轴颜色与系列一致
								}
							}
						},
						{
							type: 'value',
							name: '心率/血氧',
							min: 0,
							max: 200,
							axisLine: {
								lineStyle: {
									color: '#45B7D1' // 血氧轴颜色与系列一致
								}
							}
						}
					],
					series: [{
							name: '体温',
							type: 'line',
							yAxisIndex: 0, // 使用第一个y轴
							symbol: 'circle',
							symbolSize: 8,
							itemStyle: {
								color: '#FF6B6B'
							},
							lineStyle: {
								width: 3
							},
							// 只取前5个体温数据
							data: this.temData.map(item => item.value)
						},
						{
							name: '心率',
							type: 'line',
							yAxisIndex: 1, // 使用第二个y轴
							symbol: 'circle',
							symbolSize: 8,
							itemStyle: {
								color: '#4ECDC4'
							},
							lineStyle: {
								width: 3
							},
							// 只取前5个心率数据
							data: this.xlData.map(item => item.value)
						},
						{
							name: '血氧',
							type: 'line',
							yAxisIndex: 1, // 使用第二个y轴
							symbol: 'circle',
							symbolSize: 8,
							itemStyle: {
								color: '#45B7D1'
							},
							lineStyle: {
								width: 3
							},
							// 只取前5个血氧数据
							data: this.oxData.map(item => item.value)
						}
					]
				};
				this.initChart()
			}
		},
		onUnload() {
			// this.timer && clearInterval(this.timer)
		}
	}
</script>

<style lang="scss" scoped>
	.controll {
		width: 100%;
		height: 100vh;
		background-color: #F7F8FA;

		.title {
			height: 200rpx;
			width: 100%;
			// display: flex;
			background-color: #fff;
			box-sizing: border-box;
			padding: 20rpx;

			.l {
				display: flex;
				align-items: flex-end;

				.name {
					font-size: 40rpx;
					font-weight: bold;
				}

				.phone {
					margin-left: 20rpx;
				}
			}

			.r {
				margin-top: 10rpx;

				.car_name,
				.car_number {

					.value {
						font-size: 24rpx;
						color: #666
					}

				}

				.car_number {
					margin-top: 10rpx;
				}
			}
		}

		.content {
			display: flex;
			flex-wrap: wrap;
			box-sizing: border-box;
			padding: 20rpx;
			justify-content: space-around;

			.item {
				width: 40%;
				height: 120rpx;
				background-color: #fff;
				margin-bottom: 20rpx;
				margin-right: 20rpx;
				box-sizing: border-box;
				box-shadow: 1rpx 1rpx 2rpx #eee;
				border-radius: 10rpx;
				text-align: center;
				line-height: 120rpx;
				display: flex;
				align-items: center;
				justify-content: center;

				.btn {
					display: block;
					height: 100%;
					background-color: #eee;
					font-size: 40rpx;
					flex: 1;
				}

				.value {
					margin: 0 20rpx;
				}

				&:nth-child(2n) {
					margin-right: 0;
				}
			}
		}
	}

	.history {
		width: 100vw;
		display: flex;
		align-items: center;
		justify-content: center;

		font-size: 40rpx;
		margin: 20rpx 0;
		background-color: #eee;
		height: 100rpx;
	}

	.chart-container {
		width: 100vw;
		height: 500rpx;
	}
</style>